package io.github.igordonxiao.gateguard.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.web.access.AccessDeniedHandler;

/**
 * 资源服务器配置
 */
@Configuration
@EnableResourceServer
@EnableConfigurationProperties
public class Oauth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private AccessDeniedHandler accessDeniedHandler;

    Oauth2ResourceServerConfig(AuthAccessDeniedHandler authAccessDeniedHandler) {
        this.accessDeniedHandler = authAccessDeniedHandler;
    }

    /**
     * 配置资源服务器安全
     *
     * @param resources 资源
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources
                // 配置资源ID
                .resourceId(Config.RESOURCE_ID);
        // 配置认证异常入口
        //.authenticationEntryPoint()
        // 配置拒绝访问异常入口
        //.accessDeniedHandler();
    }

    /**
     * Web安全配置
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
        // 配置认证请求列表
        registry
                .antMatchers("/api/oauth/**")
                .permitAll()
                .antMatchers("/api/**")
                .authenticated()
                .anyRequest()
                .authenticated()
                .and()
                .logout()
//                .logoutUrl("/api/logout")
//                .logoutSuccessHandler()
                .deleteCookies("JSESSIONID")
                .and()
                .exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler);
    }

}